package com.hwy.widget.float_window

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hwy.widget.R
import com.hwy.widget.utils.LogUtil
import java.util.*

/**
 * =======================================
 * 作者: hewenyu
 * 日期: 2022/3/14 23:29
 * 说明: 显示日志
 * =======================================
 */
class FloatLogLayout(context: Context, attrs: AttributeSet? = null) :
    AbstractFloatListLayout(context, attrs), LogUtil.LogListener {

    private val dataList by lazy {
        ArrayList<String>()
    }

    private fun addLogData(data: String?) {
        dataList.add(data ?: "")
        recyclerView?.adapter?.notifyItemInserted(dataList.size - 1)
    }

    override fun initRecyclerView(recyclerView: RecyclerView?) {
        recyclerView?.run {
            layoutManager = LinearLayoutManager(context)
            adapter = FloatHttpAdapter()
        }
    }

    override fun onLog(level: Int, className: String?, msg: String?) {
        addLogData(String.format("%s: %s", className, msg))
    }

    inner class FloatHttpAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return ViewHolder(
                LayoutInflater.from(context).inflate(
                    R.layout.adapter_float_http_layout, parent, false
                )
            )
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            (holder as? ViewHolder)?.bindView(dataList[position])
        }

        override fun getItemCount(): Int {
            return dataList.size
        }
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bindView(data: String) {
            itemView.findViewById<TextView>(R.id.tv_content)?.run {
                text = data
                setOnLongClickListener {
                    copy2Clipboard(context, data)
                    Toast.makeText(context, "复制成功", Toast.LENGTH_SHORT).show()
                    return@setOnLongClickListener true
                }
            }
        }

        /**
         * 复制到剪贴板
         */
        private fun copy2Clipboard(context: Context, content: String?) {
            (context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager)?.run {
                setPrimaryClip(ClipData.newPlainText("Lable", content ?: ""))
            }
        }

    }

}
